<?php

namespace app\common;

use think\facade\Db;

/**
 * 业务逻辑帮助类
 * 处理订单审核、工单生成、客户属性计算等核心业务逻辑
 */
class BusinessHelper
{
    /**
     * 处理订单审核流程
     * 检查财务审核和合同审核状态，两者都通过后生成工单
     *
     * @param int $orderId 订单ID
     * @return array ['status' => 1/0, 'message' => string, 'work_order_id' => int|null]
     */
    public static function processOrderApproval($orderId)
    {
        // 检查财务审核状态
        $financeVerified = self::checkFinanceVerified($orderId);

        // 检查合同审核状态
        $contractVerified = self::checkContractVerified($orderId);

        // 只有两个审核都通过，才能生成工单
        if ($financeVerified && $contractVerified) {
            // 审核通过，生成工单
            $workOrderId = self::generateWorkOrder($orderId);

            // 更新客户属性
            $order = Db::name('crm_order')->find($orderId);
            self::calculateCustomerAttribute($order['customer_id']);

            return [
                'status' => 1,
                'message' => '审核通过，工单已生成',
                'work_order_id' => $workOrderId
            ];
        }

        if (!$financeVerified && !$contractVerified) {
            return [
                'status' => 0,
                'message' => '财务审核和合同审核均未通过'
            ];
        } elseif (!$financeVerified) {
            return [
                'status' => 0,
                'message' => '财务审核未通过'
            ];
        } else {
            return [
                'status' => 0,
                'message' => '合同审核未通过'
            ];
        }
    }

    /**
     * 检查财务审核状态
     *
     * @param int $orderId 订单ID
     * @return bool
     */
    public static function checkFinanceVerified($orderId)
    {
        // 检查是否有已核实的财务记录
        $hasFinanceRecord = Db::name('crm_finance_record')
            ->where('order_id', $orderId)
            ->where('verification_status', 1)
            ->count() > 0;

        // 如果订单金额为0（免费订单），则不需要财务审核
        $order = Db::name('crm_order')->field('total_amount')->find($orderId);
        if ($order && $order['total_amount'] == 0) {
            return true;
        }

        return $hasFinanceRecord;
    }

    /**
     * 检查合同审核状态
     *
     * @param int $orderId 订单ID
     * @return bool
     */
    public static function checkContractVerified($orderId)
    {
        // 检查合同归档状态
        $contractVerified = Db::name('crm_contract_archive')
            ->where('order_id', $orderId)
            ->where('archive_status', 1)
            ->count() > 0;

        return $contractVerified;
    }

    /**
     * 生成工单
     *
     * @param int $orderId 订单ID
     * @return int|false 工单ID或false
     */
    public static function generateWorkOrder($orderId)
    {
        $order = Db::name('crm_order')->find($orderId);
        if (!$order) {
            return false;
        }

        // 生成工单编号
        $workOrderNo = self::generateWorkOrderNo();

        // 根据订单类型确定工单类别
        $category = 1;  // 默认案件委托工单
        if (in_array($order['order_sub_type'], [2, 3])) {
            $category = 2;  // 法务工单
        }

        $workOrderData = [
            'order_id' => $orderId,
            'work_order_no' => $workOrderNo,
            'category' => $category,
            'title' => '订单[' . $order['order_no'] . ']处理工单',
            'description' => '订单总金额：' . $order['total_amount'] . '元，已支付金额：' . $order['paid_amount'] . '元',
            'status' => 1,  // 待分配
            'priority' => 2,  // 中等
            'customer_id' => $order['customer_id'],
            'customer_name' => $order['customer_name'],
            'create_time' => time(),
            'update_time' => time()
        ];

        $workOrderId = Db::name('work_order')->insertGetId($workOrderData);

        if ($workOrderId) {
            // 记录工单创建进度
            Db::name('work_order_progress')->insert([
                'work_order_id' => $workOrderId,
                'operator_id' => 0,  // 系统操作
                'operator_name' => '系统',
                'progress_type' => 1,
                'new_status' => 1,
                'content' => '订单审核通过，工单已创建',
                'create_time' => time()
            ]);

            // 更新订单状态
            Db::name('crm_order')->where('id', $orderId)->update([
                'delivery_status' => 1,  // 交付中
                'update_time' => time()
            ]);

            // 自动分配给部门经理
            self::autoAssignWorkOrder($workOrderId);
        }

        return $workOrderId;
    }

    /**
     * 自动分配工单给部门经理
     *
     * @param int $workOrderId 工单ID
     * @return bool
     */
    public static function autoAssignWorkOrder($workOrderId)
    {
        $workOrder = Db::name('work_order')->find($workOrderId);
        if (!$workOrder) {
            return false;
        }

        // 根据工单类别确定部门
        $departmentMap = [
            1 => 3,  // 案件委托工单 -> 诉讼部
            2 => 4   // 法务工单 -> 法务部
        ];

        $departmentId = $departmentMap[$workOrder['category']] ?? 0;

        // 获取部门经理
        $manager = Db::name('department_admin')
            ->where('department_id', $departmentId)
            ->find();

        if ($manager) {
            Db::name('work_order')->where('id', $workOrderId)->update([
                'department_manager_id' => $manager['admin_id'],
                'update_time' => time()
            ]);

            // 记录分配历史
            Db::name('work_order_assignment_history')->insert([
                'work_order_id' => $workOrderId,
                'from_assignee_id' => null,
                'to_assignee_id' => null,
                'assignment_type' => 'auto_assign',
                'operator_id' => 0,
                'create_time' => time()
            ]);
        }

        return true;
    }

    /**
     * 计算客户属性
     * 普通客户 -> 合作客户（产生案件委托订单）
     * 合作客户 -> 会员客户（产生法务订单）
     *
     * @param int $customerId 客户ID
     * @return int 客户属性值
     */
    public static function calculateCustomerAttribute($customerId)
    {
        // 检查是否有案件委托订单
        $hasLawsuitOrder = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->where('order_sub_type', 1)
            ->where('approval_status', 2)
            ->count();

        // 检查是否有法务订单
        $hasLegalOrder = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->where('order_sub_type', 2)
            ->where('approval_status', 2)
            ->count();

        $attribute = 1;  // 默认为普通客户
        if ($hasLegalOrder > 0) {
            $attribute = 3;  // 会员客户
        } elseif ($hasLawsuitOrder > 0) {
            $attribute = 2;  // 合作客户
        }

        // 更新客户属性
        Db::name('crm_customer')->where('id', $customerId)->update([
            'customer_attribute' => $attribute,
            'update_time' => time()
        ]);

        return $attribute;
    }

    /**
     * 检查会员是否可以下免费法务专项订单
     *
     * @param int $customerId 客户ID
     * @param int $orderType 订单类型
     * @return array ['can_use' => bool, 'message' => string]
     */
    public static function checkMemberFreeOrder($customerId, $orderType)
    {
        // 只有法务专项订单才有免费服务
        if ($orderType != 3) {
            return ['can_use' => false, 'message' => '仅法务专项订单可享受会员免费服务'];
        }

        // 检查客户是否为会员
        $customer = Db::name('crm_customer')
            ->where('id', $customerId)
            ->find();

        if (!$customer || $customer['customer_attribute'] != 3) {
            return ['can_use' => false, 'message' => '非会员客户'];
        }

        // 检查会员是否在服务期内
        $membership = Db::name('customer_membership')
            ->where('customer_id', $customerId)
            ->where('status', 1)
            ->where('service_end_date', '>', time())
            ->find();

        if (!$membership) {
            return ['can_use' => false, 'message' => '会员服务已过期'];
        }

        // 在服务期内，可以下免费订单
        return ['can_use' => true, 'message' => '可享受免费法务专项服务'];
    }

    /**
     * 检查用户是否有客户信息审核权限
     * 条件：超级管理员 OR 拥有客户审核权限的用户 OR 部门经理
     *
     * @param int $userId 用户ID
     * @return bool
     */
    public static function checkCustomerReviewPermission($userId)
    {
        // 超级管理员（group_id=1）默认有权限
        $user = Db::name('admin')->where('id', $userId)->find();
        if (!$user) return false;

        if ($user['group_id'] == 1) {  // 超级管理员
            return true;
        }

        // 检查是否拥有客户审核权限（预留权限点）
        $hasPermission = Db::name('admin_rule')
            ->where('name', 'crm.customer.review')
            ->where('uids', 'like', '%' . $userId . '%')
            ->count();

        if ($hasPermission > 0) {
            return true;
        }

        // 部门经理默认可以审核
        if ($user['group_id'] == 2) {  // 部门经理
            return true;
        }

        return false;
    }

    /**
     * 检查会员是否在服务期内
     *
     * @param int $customerId 客户ID
     * @return bool
     */
    public static function checkMembershipActive($customerId)
    {
        $membership = Db::name('customer_membership')
            ->where('customer_id', $customerId)
            ->where('status', 1)
            ->where('service_end_date', '>', time())
            ->find();

        return $membership ? true : false;
    }

    /**
     * 生成工单编号
     *
     * @return string
     */
    public static function generateWorkOrderNo()
    {
        $prefix = 'WO';
        $date = date('Ymd');
        $lastOrder = Db::name('work_order')
            ->where('work_order_no', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->find();

        if ($lastOrder) {
            $lastNo = substr($lastOrder['work_order_no'], -6);
            $seq = str_pad($lastNo + 1, 6, '0', STR_PAD_LEFT);
        } else {
            $seq = '000001';
        }

        return $prefix . $date . $seq;
    }

    /**
     * 生成订单编号
     *
     * @return string
     */
    public static function generateOrderNo()
    {
        $prefix = 'ORD';
        $date = date('Ymd');
        $lastOrder = Db::name('crm_order')
            ->where('order_no', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->find();

        if ($lastOrder) {
            $lastNo = substr($lastOrder['order_no'], -6);
            $seq = str_pad($lastNo + 1, 6, '0', STR_PAD_LEFT);
        } else {
            $seq = '000001';
        }

        return $prefix . $date . $seq;
    }

    /**
     * 记录工单分配历史
     *
     * @param int $workOrderId 工单ID
     * @param int|null $fromAssigneeId 原分配人ID
     * @param int $toAssigneeId 新分配人ID
     * @param string $type 分配类型
     * @param int $operatorId 操作人ID
     * @param string $remark 备注
     * @return int|false
     */
    public static function recordWorkOrderAssignment($workOrderId, $fromAssigneeId, $toAssigneeId, $type, $operatorId, $remark = '')
    {
        return Db::name('work_order_assignment_history')->insertGetId([
            'work_order_id' => $workOrderId,
            'from_assignee_id' => $fromAssigneeId,
            'to_assignee_id' => $toAssigneeId,
            'assignment_type' => $type,
            'operator_id' => $operatorId,
            'remark' => $remark,
            'create_time' => time()
        ]);
    }

    /**
     * 获取客户统计信息
     *
     * @param int $customerId 客户ID
     * @return array
     */
    public static function getCustomerStats($customerId)
    {
        // 总订单数
        $totalOrders = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->count();

        // 已完成订单数
        $completedOrders = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->where('delivery_status', 2)
            ->count();

        // 总工单数
        $totalWorkOrders = Db::name('work_order')
            ->where('customer_id', $customerId)
            ->count();

        // 已完成工单数
        $completedWorkOrders = Db::name('work_order')
            ->where('customer_id', $customerId)
            ->where('status', 3)
            ->count();

        // 总消费金额
        $totalAmount = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->where('approval_status', 2)
            ->sum('total_amount');

        return [
            'total_orders' => $totalOrders,
            'completed_orders' => $completedOrders,
            'total_work_orders' => $totalWorkOrders,
            'completed_work_orders' => $completedWorkOrders,
            'total_amount' => $totalAmount
        ];
    }
}
